﻿using System;
using System.Windows.Data;
using Moria.Common.Enum;
using System.Reflection;
using System.ComponentModel;

namespace Moria.Silverlight.Converters
{
    public class EnumConverter: IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string rtrn = string.Empty;
            if (value != null)
            {
                rtrn = Description(value);
            }
            return rtrn;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int n = 0;
            return Gender.Unknown;
        }

        private static string Description(object value)
        {
            Type type = value.GetType();
            FieldInfo fieldInfo = type.GetField(value.ToString());
            DescriptionAttribute[] descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (descriptionAttributes != null && descriptionAttributes.Length > 0)
                return descriptionAttributes[0].Description;
            return fieldInfo.GetValue(value).ToString();
        }

    }
}
